﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfCropImage
{
    /// <summary>
    /// CutImageEx.xaml 的交互逻辑
    /// </summary>
    public partial class CutImageEx : Window
    {
        public CutImageEx(System.Drawing.Bitmap bitmap)
        {
            InitializeComponent();
            resImage = null;
            InitImageInfo(bitmap);
            addEvent();
        }

        /// <summary>
        /// 是否绘制过程中
        /// </summary>
        private bool isDrawing;
        /// <summary>
        ///   //绘制起始点
        /// </summary>
        private Point startPoint = new Point();
        /// <summary>
        /// //基于原点的坐标
        /// </summary>
        private Point leftPoint = new Point();

        /// <summary>
        ///   //缩放比例
        /// </summary>
        private double zoom = 1.0;
        /// <summary>
        ///  //缩放后的宽度
        /// </summary>
        private double zoomW = 0;
        /// <summary>
        ///  //缩放后的高度
        /// </summary>
        private double zoomH = 0;
        /// <summary>
        ///   //原图
        /// </summary>
        private System.Drawing.Image originImage;
        public static System.Drawing.Bitmap resImage { get; private set; }
        /// <summary>
        /// 画布事件添加
        /// </summary>
        private void addEvent()
        {
            canvas.MouseDown += canvas_MouseDown;
            canvas.MouseUp += canvas_MouseUp;
            canvas.MouseMove += canvas_MouseMove;
        }
        /// <summary>
        /// 画布事件移除
        /// </summary>
        private void removeEvent()
        {
            canvas.MouseDown -= canvas_MouseDown;
            canvas.MouseUp -= canvas_MouseUp;
            canvas.MouseMove -= canvas_MouseMove;
        }

        /// <summary>
        /// 鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                startPoint = e.GetPosition(canvas);
                startPoint = checkPoint(startPoint);
                //rectangle = new Rectangle();
                // rectangle.Stroke = Brushes.Red;
                // rectangle.StrokeThickness = 1;
                Canvas.SetLeft(rectangle, startPoint.X);
                Canvas.SetTop(rectangle, startPoint.Y);
                //canvas.Children.Add(rectangle);
                // panel = new StackPanel();

                SolidColorBrush mybtn1_Brush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 140, 0));
                panel.Background = (System.Windows.Media.Brush)mybtn1_Brush;
                panel.Opacity = 0.3;

                Canvas.SetLeft(panel, startPoint.X);
                Canvas.SetTop(panel, startPoint.Y);
                //canvas.Children.Add(panel);
                isDrawing = true;
            }
        }
        /// <summary>
        /// 鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDrawing)
            {
                Point currentPoint = e.GetPosition(canvas);
                currentPoint = checkPoint(currentPoint);
                double width = currentPoint.X - startPoint.X;
                double height = currentPoint.Y - startPoint.Y;


                if (width < 0)
                {
                    Canvas.SetLeft(rectangle, currentPoint.X);
                    rectangle.Width = Math.Abs(width);
                    leftPoint.X = currentPoint.X;
                    panel.Width = rectangle.Width;
                    Canvas.SetLeft(panel, currentPoint.X);
                }
                else
                {
                    leftPoint.X = startPoint.X;
                    rectangle.Width = width;
                    panel.Width = rectangle.Width;
                }

                if (height < 0)
                {
                    Canvas.SetTop(rectangle, currentPoint.Y);
                    rectangle.Height = Math.Abs(height);
                    leftPoint.Y = currentPoint.Y;
                    panel.Height = rectangle.Height;
                    Canvas.SetTop(panel, currentPoint.Y);
                }
                else
                {
                    leftPoint.Y = startPoint.Y;
                    rectangle.Height = height;
                    panel.Height = rectangle.Height;
                }
            }
        }
        /// <summary>
        /// 鼠标弹起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (isDrawing)
            {
                isDrawing = false;
                //removeEvent();
                LoadImage();
            }
        }


        /// <summary>
        /// 选取图片后，加载图片信息
        /// </summary>
        public void InitImageInfo(System.Drawing.Bitmap bitmap)
        {
            var bitmap2 = (System.Drawing.Bitmap)bitmap.Clone();
            var bitmapimg = ImageHelper.Bitmap2BitMapImage(bitmap);
            img.Source = bitmapimg;

            originImage = bitmap2; //从文件加载原图
            zoomW = originImage.Width;
            zoomH = originImage.Height;
            zoom = 1.0;
            if (originImage.Width > originImage.Height)
            {
                if (originImage.Width > 500)
                {
                    zoom = originImage.Width / 500.0;
                    zoomW = 500;
                    zoomH = (int)(originImage.Height / zoom);
                }
            }
            else
            {
                if (originImage.Height > 500)
                {
                    zoom = originImage.Height / 500.0;
                    zoomH = 500;
                    zoomW = (int)(originImage.Width / zoom);
                }
            }
        }
      
        /// <summary>
        /// 裁剪后图片展示
        /// </summary>
        /// <param name="img"></param>
        public void LoadImage()
        {
            try
            {
                //创建矩形对象表示原图上裁剪的矩形区域，这里相当于划定原图上坐标为(10, 10)处，50x50大小的矩形区域为裁剪区域
                var r = getFixRectangle(originImage, leftPoint, rectangle);
                resImage = ImageHelper.CropImage(originImage, r);
                // resImage.Save("D:/1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                var res1 = (System.Drawing.Bitmap)resImage.Clone();
                BitmapImage bitmapImage;
                using (MemoryStream memory = new MemoryStream())
                {
                    res1.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
                    bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    memory.Seek(0, SeekOrigin.Begin);
                    bitmapImage.StreamSource = memory;
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                }

                bitmapImage.Freeze();
                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    imgsamll.Source = bitmapImage;

                }));
            }
            catch (Exception)
            {
                   
            }
        }
        /// <summary>
        /// 自动去黑边-不靠谱
        /// </summary>
        /// <param name="bitmap"></param>
        private void AutoCutBitMap(System.Drawing.Bitmap bitmap)
        {
            var bitmap2 = (System.Drawing.Bitmap)bitmap.Clone();
            System.Drawing.Bitmap bmp = ImageHelper.AutoCutColorEdge2(bitmap2, System.Drawing.Color.White, 0.2, 0.3);
            bmp = ImageHelper.AutoCutColorEdge2(bmp, System.Drawing.Color.Black, 0.2, 0.3);
            bmp = ImageHelper.AutoCutColorEdge4(bmp, System.Drawing.Color.Gray, 0.2, 0.3);
           
            BitmapImage bitmapImage;
            using (MemoryStream memory = new MemoryStream())
            {
                bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
                bmp.Dispose();
                bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                memory.Seek(0, SeekOrigin.Begin);
                bitmapImage.StreamSource = memory;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
            }

            bitmapImage.Freeze();
            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                imgsamll.Source = bitmapImage;

            }));
        }
        /// <summary>
        /// 判断点位超出
        /// </summary>
        /// <param name="p"></param>
        public Point checkPoint(Point p)
        {
            if (p.X > zoomW)
            {
                p.X = zoomW;
            }
            if (p.X < 0)
            {
                p.X = 0;
            }
            if (p.Y > zoomH)
            {
                p.Y = zoomH;
            }
            if (p.Y < 0)
            {
                p.X = 0;
            }
            return p;
        }

        /// <summary>
        /// 获取裁剪区域
        /// </summary>
        /// <param name="originImage"></param>
        /// <returns></returns>
        public System.Drawing.Rectangle getFixRectangle(System.Drawing.Image originImage, Point startPoint, Rectangle rectangle)
        {
            int x = (int)(startPoint.X * zoom);
            int y = (int)(startPoint.Y * zoom);
            int w = (int)(rectangle.Width * zoom);
            int h = (int)(rectangle.Height * zoom);
            System.Drawing.Rectangle r = new System.Drawing.Rectangle(x, y, w, h);
            return r;
        }
        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (resImage == null)
            {
                MessageBox.Show("请截取图片！");
            }
            this.Close();
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            resImage = null;
            this.Close();
        }
    }
}
